package com.githan.bootsecurity.config;

import com.alibaba.fastjson.JSON;
import com.githan.bootsecurity.response.Result;
import com.githan.bootsecurity.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author https://github.com/Han56
 * @date 2021/4/11 14:52
 * 自定义登录成功处理器类（登录成功操作）
 */
@Component
public class MyAuthenticationSuccessHandler extends JSONAuthentication implements AuthenticationSuccessHandler {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        Result result = Result.ok().message("登录成功");
        //从前端获取用户名
        String username = httpServletRequest.getParameter("username");
        List<String> returnRoleList = sysUserService.getRoleCodeByusername(username);
        List<String> returnNameList = sysUserService.getRoleNameByUsername(username);
        String returnName = returnNameList.toString().substring(1,returnNameList.toString().length()-1);
        String returnRole = returnRoleList.toString().substring(1,returnRoleList.toString().length()-1);
        String returnArea = sysUserService.getUserAreaByUsername(username);
        result.setName(returnName);
        result.setRole(returnRole);
        result.setArea(returnArea);
        //处理编码方式，防止中文乱码的情况
        this.WriteJSON(httpServletRequest,httpServletResponse,result);
    }
}
